package hr.fer.zpr.nmbp.project2.dao;

import hr.fer.zpr.nmbp.project2.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project2.model.Bolnica;
import hr.fer.zpr.nmbp.project2.model.Lijecnik;

import java.util.List;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class BolnicaDAO {

	private Session session;
	
	public BolnicaDAO(Session session) {
		this.session = session;
	}
    
    public void save(Bolnica bolnica) {
    	
    	if(bolnica.getSifra() == null || bolnica.getSifra().isEmpty()) {
			throw new PrimaryKeyConstraintException("Šifra bolnice ne smije biti NULL");
		}
		
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(bolnica);
            tx.commit();
        } catch (ConstraintViolationException e) {
            if (tx != null) tx.rollback();
            throw new PrimaryKeyConstraintException("Šifra bolnice već postoji u bazi podataka");
        }
    }
    
    public void delete(Bolnica bolnica) {
    	Transaction tx = null;
        try {
            tx = session.beginTransaction();
            
            List<Lijecnik> lijecnici = bolnica.getLijecnici();
    	
            for(Lijecnik lijecnik : lijecnici){
                if(lijecnik.getBolnica().equals(bolnica)){
                    lijecnik.setBolnica(null);
                    session.merge(lijecnik);
                }
            }
            
            session.delete(bolnica);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * Samo gleda šifru.
     * @param bolnicaPrototype
     * @return 
     */
    public List<Bolnica> load(Bolnica bolnicaPrototype) {    	
    	Properties prop = new Properties();
        StringBuilder sb = new StringBuilder();
        sb.append("select b from Bolnica as b");
        if (bolnicaPrototype.getSifra() != null) {
            sb.append(" where b.sifra = :sifra");
            prop.put("sifra", bolnicaPrototype.getSifra());
        }
                                        
        return (List<Bolnica>) session.createQuery(sb.toString()).setProperties(prop).list();
    }
    
    public List<Bolnica> loadAll() {    	
    	return (List<Bolnica>) session.createQuery("select b from Bolnica as b").list();
    }
    
}
